from flask import Blueprint, render_template, jsonify, request,session, redirect, url_for, render_template_string
from datetime import datetime, timedelta
from app.log_query import get_error_logs,get_error_logs2,get_error_logs3
import pytz
from functools import wraps  # 添加这行导入
from app.logger import get_logger
from app.tools.time_util import local_string_to_utc

logger = get_logger('views')

bp = Blueprint('web', __name__)

# 依赖注入
es_client = None
config = None

def init_views(es, conf):
    global es_client, config
    es_client = es
    config = conf

# 认证装饰器
def require_session_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        print(f"请求路径: {request.path}")
        print(f"Session内容: {dict(session)}")
        print(f"Session Cookie: {request.cookies.get('session')}")
        print(f"所有Cookie: {dict(request.cookies)}")
        print(f"logged_in值: {session.get('logged_in')}")
        if not session.get('logged_in'):
            # 通过URL路径判断是否为API请求
            is_api = request.path.startswith('/api/')
            
            if is_api:
                return jsonify({
                    'error': 'unauthorized', 
                    'message': '请重新登录',
                    'redirect': url_for('web.login')
                }), 401
            else:
                return redirect(url_for('web.login'))
        return f(*args, **kwargs)
    return decorated

def check_auth(username, password):
    # 从配置读取
    config_auth = config.get_auth_config()  # 假设认证配置在这里
    logger.info(f"config_auth: {config_auth.get('username') }, {config_auth.get('password')}")
    logger.info(f"username: {username}, password: {password}")
    return username == config_auth.get('username') and password == config_auth.get('password')


@bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        if check_auth(username, password):
            session['logged_in'] = True
            session['username'] = username
            print(f"Session内容: {dict(session)}")
            print(f"Session ID: {request.cookies.get('session')}")
            return redirect(url_for('web.index'))
        return render_template('login.html', error='用户名或密码错误')
    
    return render_template('login.html')

@bp.route('/logout')
def logout():
    session.pop('logged_in', None)
    return redirect(url_for('web.login'))



@bp.route('/')
def index():
    if not session.get('logged_in'):
        return redirect(url_for('web.login'))
    return render_template('index.html')

@bp.route('/api/status')
@require_session_auth
def get_status():
    try:
        es_status = "connected" if es_client.ping() else "disconnected"
        end_time = datetime.utcnow()
        end_time = end_time.replace(minute=0, second=0, microsecond=0) + timedelta(hours=1)
        logger.info(f"end_time: {end_time}")
        start_time = end_time - timedelta(hours=24)
        # error_logs = get_error_logs2(
        #     es_client=es_client,
        #     index_pattern=config.get_es_config()['index_pattern'],
        #     start_time=start_time,
        #     end_time=end_time
        # )
        total_errors_24h = 0
        hourly_stats = {}
        local_timezone = pytz.timezone('Asia/Shanghai')
        for i in range(24):
            hour_start = end_time - timedelta(hours=i+1)
            hour_end = end_time - timedelta(hours=i)
            # logger.info(f"hour_start: {hour_start}")
            # logger.info(f"hour_start str: {hour_start.replace(tzinfo=pytz.utc).astimezone(local_timezone).strftime('%Y-%m-%d %H:00')}")
            hour_logs = get_error_logs2(
                es_client=es_client,
                index_pattern=config.get_es_config()['index_pattern'],
                start_time=hour_start,
                end_time=hour_end
            )
            total_errors_24h += len(hour_logs)
            # hour_start时间utc，转换为本地时间
            hourly_stats[hour_start.replace(tzinfo=pytz.utc).astimezone(local_timezone).strftime('%Y-%m-%d %H:00')] = len(hour_logs)
        return jsonify({
            'es_status': es_status,
            'total_errors_24h': total_errors_24h,
            'hourly_stats': hourly_stats,
            'last_check': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        })
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@bp.route('/api/logs')
@require_session_auth
def get_logs():
    try:
         # 优先用 start/end，否则用 hours
        start_str = request.args.get('start')
        end_str = request.args.get('end')
        pageIndex = request.args.get('pageIndex', 1, type=int)
        hours = request.args.get('hours', 1, type=int)
        limit = request.args.get('limit', 50, type=int)

        if start_str:
            logger.info(f"start_str: {start_str}")
            # 解析为 datetime 2025-06-23 00:00 , 得到的时间是本地时间，转换为utc时区
            start_time = local_string_to_utc(start_str)
            #end_time 为start_time加一小时
            end_time = start_time + timedelta(hours=1)
        else:
            end_time = datetime.utcnow()
            start_time = end_time - timedelta(hours=hours)
        logger.info(f"start_time: {start_time}, end_time: {end_time}")
        response = get_error_logs3(
            es_client=es_client,
            index_pattern=config.get_es_config()['index_pattern'],
            start_time=start_time,
            end_time=end_time,
            pageIndex=pageIndex,
            size=limit
        )
        #打印输出内容
        logger.info(f"error_logs: {response[1]}")
        formatted_logs = []
        for log in response[0]:
            source = log.get('_source', {})
            formatted_logs.append({
                'timestamp': source.get('@timestamp', 'N/A'),
                'message': source.get('message', 'N/A'),
                'level': 'ERROR',
                'source': source
            })
        return jsonify({
            'logs': formatted_logs,
            'total': response[1],
            'query_time': {
                'start': start_time.isoformat(),
                'end': end_time.isoformat()
            }
        })
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@bp.route('/api/config')
@require_session_auth
def get_config():
    safe_config = {
        'elasticsearch': {
            'host': config.get_es_config()['host'],
            'port': config.get_es_config()['port'],
            'index_pattern': config.get_es_config()['index_pattern']
        },
        'alerting': {
            'recipients': config.get_alerting_config()['recipients'],
            'subject_prefix': config.get_alerting_config()['subject_prefix']
        }
    }
    return jsonify(safe_config) 